package Basic.day04;

import java.util.Random;
import java.util.Scanner;

public class GuessWhat {
    public static void main(String[] args) {
        //猜猜这个数是多少
        int numberToGuess = 21;

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数据范围：");
        int range = sc.nextInt();
        Random random = new Random();
        int num = random.nextInt(range+1);
//        for (int i = 0; i < 1; i--) {
//            System.out.println("猜猜这个数是多少");
//            int num = sc.nextInt();
//            if (num > numberToGuess) {
//                System.out.println("你猜的数太大了，重猜");
//            } else if (num < numberToGuess) {
//                System.out.println("你猜的数太小了，重猜");
//            } else {
//                System.out.println("恭喜你，猜对了");
//                break;
//            }
//        }

//       num    1 2 3 4 5 6 7 8 9 10 mid=5 1-4 原11 0-4+6 5
//       index  0 1 2 3 4 5 6 7 8 9
        //二分查找法
        int arr[] = new int[range+1];
        for (int i = 0; i < arr.length - 1; i++) {
            arr[i] = i+1;
        }
        int low = 0;
        int high = arr.length-1;
        int mid =  (low+high)/2;
        for (int i = 0; i < arr.length; i++){
            if (arr[mid] < numberToGuess && low < high){
                System.out.println("我猜："+ num);
                System.out.println("你猜的数太大了，重猜");
                low = mid+1;
                num = random.nextInt(range+1-mid+1)+mid+1;
                System.out.println((0+mid+1) + "~" + (range+1-mid+1+mid+1));
                mid = (low+high)/2;
            } else if (arr[mid] > numberToGuess && low < high){
                System.out.println("我猜："+ num);
                System.out.println("你猜的数太大了，重猜");
                high = mid - 1;
                num = random.nextInt(range+1-mid+1);
                mid = (low+high)/2;
            } else if (arr[mid] == numberToGuess){
                System.out.println("恭喜你，猜对了");
                break;
            }
        }
        System.out.println("正确的数字是："+num);


    }
}
